<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Board extends CI_Controller {

    protected $posts_per_page = 10;
    public $validation_errors = array();

    public function index()
    {
	$this->load->view('board/categories');
    }

    public function cats()
    {
	$categories = $this->db->query("SELECT category_id, category_title, category_posts_count  FROM categories");


	$this->load->view('header');
	$this->load->view('board/categories', array('cats' => $categories->result_array()));
	$this->load->view('footer');
    }

    public function cat($cat_id, $page = 0)
    {

	$sql = 'SELECT post_id, post_category_id, post_title,post_text,post_date,post_end_date,post_enabled,post_user FROM posts WHERE post_category_id = ? LIMIT ?, ?';
	$posts = $this->db->query($sql,array(
					     $cat_id,
					     (int)$page,
					     (int)$this->posts_per_page)
				  );

	$cat = $this->db->query('SELECT category_id, category_title, category_posts_count  FROM categories WHERE category_id = ?', array($cat_id));


	$this->load->view('header');
	$this->load->view('board/category', array(
						  'posts' => $posts->result_array(),
						  'cat' => $cat->row()
						  ));
	$this->load->view('footer');
    }

    public function add_post() 
    {
	if (isset($_POST)) {
	    if ($this->validate_post()) {
		$this->save_post();
		$this->load->view('header');
		$this->load->view('board/add_ok');
		$this->load->view('footer');

	    }
	    else {
		$categories = $this->db->query("SELECT category_id, category_title, category_posts_count  FROM categories");
		$this->load->view('header');
		$this->load->view('board/add_post', array('cats' => $categories->result_array()));
		$this->load->view('footer');
	    }
	}
	else {
	    $categories = $this->db->query("SELECT category_id, category_title, category_posts_count  FROM categories");
	    $this->load->view('header');
	    $this->load->view('board/add_post', array('cats' => $categories->result_array()));
	    $this->load->view('footer');
	}

    }

    protected function save_post() {
    }
	
    protected function validate_post() {
	$this->load->helper(array('form', 'url'));
	$this->load->library('form_validation');

	$this->form_validation->set_rules('post_title', 'Post title', 'required');
	$this->form_validation->set_rules('post_text', 'Post text', 'required');
	$this->form_validation->set_rules('post_category_id', 'Post category', 'required');

	return $this->form_validation->run();
    }


}

